package com.springboot.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springboot.db.entity.User;
import com.springboot.db.entity.UserExample;
import com.springboot.db.mapper.UserMapper;
import com.springboot.dubbo.consumer.UserConsumer;
import com.springboot.mapper.UserCustomMapper;
import com.springboot.service.UserService;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;

/**
 * 用户服务类
 *
 * @author supu
 * @create 2019-01-03 18:00
 **/
@Log4j2
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCustomMapper userCustomMapper;
    @Autowired
    private UserConsumer userConsumer;

    @Override
    public List<User> selectUsers() {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdLessThan(3);
        return userMapper.selectByExample(example);
    }

    @Override
    public User selectUserById(Integer id) {
        return userCustomMapper.selectUserById(id);
    }

    // timeoutMills = 300000,
    @Override
    @GlobalTransactional(name = "bootConsumer")
//    @GlobalDistributedTransaction
    public void updateUser(Integer id, boolean isRollback1, boolean isRollback2) {
        log.warn("开始全局事务，XID = {}", RootContext.getXID());

        updateUser(id);

        if(isRollback1){
            throw new RuntimeException("isRollback1 测试事务回滚");
        }

        userConsumer.saveUser();

        userConsumer.updateUser(id-1);

        if(isRollback2){
            throw new RuntimeException("isRollback2 测试事务回滚");
        }
    }

    @Override
    @GlobalTransactional
//    @GlobalDistributedTransaction
    public void saveUser(Integer id, boolean isRollback1, boolean isRollback2) {
        log.warn("开始全局事务，XID = {}", RootContext.getXID());

        userConsumer.saveUser();

        if(isRollback1){
            throw new RuntimeException("isRollback1 测试事务回滚");
        }

        updateUser(id);

        userConsumer.updateUser(id-1);

        if(isRollback2){
            throw new RuntimeException("isRollback2 测试事务回滚");
        }
    }

    @Override
    public void updateUser(Integer id) {
        User user = selectUserById(id);
        user.setName(user.getName() + id);

        userMapper.updateByPrimaryKeySelective(user);
    }
}
